﻿#region Microsoft Public License (Ms-PL)

// Microsoft Public License (Ms-PL)
// 
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
// 
// * Definitions
//      The terms "reproduce," "reproduction," "derivative works," and "distribution" 
//      have the same meaning here as under U.S. copyright law. A "contribution" is 
//      the original software, or any additions or changes to the software. A 
//      "contributor" is any person that distributes its contribution under this license. 
//      "Licensed patents" are a contributor's patent claims that read directly on its 
//      contribution.
// 
// * Grant of Rights
// 
// (A) Copyright Grant- Subject to the terms of this license, including the license 
//      conditions and limitations in section 3, each contributor grants you a non-     
//      exclusive, worldwide, royalty-free copyright license to reproduce its 
//      contribution, prepare derivative works of its contribution, and distribute its 
//      contribution or any derivative works that you create.
// 
// (B) Patent Grant- Subject to the terms of this license, including the license 
//      conditions and limitations in section 3, each contributor grants you a non-
//      exclusive, worldwide, royalty-free license under its licensed patents to make, 
//      have made, use, sell, offer for sale, import, and/or otherwise dispose of its 
//      contribution in the software or derivative works of the contribution in the 
//      software.
// 
// * Conditions and Limitations
// 
// (A) No Trademark License- This license does not grant you rights to use any 
//      contributors' name, logo, or trademarks.
// 
// (B) If you bring a patent claim against any contributor over patents that you 
//      claim are infringed by the software, your patent license from such contributor 
//      to the software ends automatically.
// 
// (C) If you distribute any portion of the software, you must retain all copyright, 
//      patent, trademark, and attribution notices that are present in the software.
// 
// (D) If you distribute any portion of the software in source code form, you may do 
//      so only under this license by including a complete copy of this license with 
//      your distribution. If you distribute any portion of the software in compiled or 
//      object code form, you may only do so under a license that complies with this 
//      license.
// 
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors 
//      give no express warranties, guarantees, or conditions. You may have 
//      additional consumer rights under your local laws which this license cannot 
//      change. To the extent permitted under your local laws, the contributors 
//      exclude the implied warranties of merchantability, fitness for a particular 
//      purpose and non-infringement.

#endregion

using System;
using System.Collections;
using System.Collections.Generic;

namespace Porticle.Generic.TreeStructure
{
    /// <summary>
    /// A Collection of childnodes.
    /// </summary>
    /// <typeparam name="TThis">The type of the node that contains these childnodes.</typeparam>
    /// <typeparam name="TChild">The type of the child nodes.</typeparam>
    internal class ChildCollection<TThis, TChild> : IList<TChild>
        where TChild : class, IHasParent<TThis, TChild>
        where TThis : class, IHasChildren<TThis, TChild>
    {
        /// <summary>
        /// The internal list of childnodes.
        /// </summary>
        private readonly List<TChild> internalChildren = new List<TChild>();

        /// <summary>
        /// The owner node of this list.
        /// </summary>
        private readonly TThis listOwner;

        /// <summary>
        /// Initializes a new instance of the <see cref="ChildCollection{TThis,TChild}"/> class.
        /// </summary>
        /// <param name="listOwner">The list owner.</param>
        public ChildCollection(TThis listOwner)
        {
            this.listOwner = listOwner;
        }

        /// <summary>
        /// Gets the first child.
        /// </summary>
        /// <value>The first child.</value>
        public TChild FirstChild
        {
            get
            {
                if (this.Count <= 0)
                {
                    throw new InvalidOperationException("There are no childnodes in the list");
                }
                return this.internalChildren[0];
            }
        }

        /// <summary>
        /// Gets the last child.
        /// </summary>
        /// <value>The last child.</value>
        public TChild LastChild
        {
            get
            {
                if (this.Count <= 0)
                {
                    throw new InvalidOperationException("There are no childnodes in the list");
                }
                return this.internalChildren[this.internalChildren.Count - 1];
            }
        }

        #region IList<TChild> Members

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        IEnumerator<TChild> IEnumerable<TChild>.GetEnumerator()
        {
            return this.internalChildren.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable) this.internalChildren).GetEnumerator();
        }

        /// <summary>
        /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public void Add(TChild item)
        {
            this.SetParent(item);
            this.internalChildren.Add(item);
        }

        /// <summary>
        /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public void Clear()
        {
            foreach (var internalChild in this.internalChildren)
            {
                this.RemoveParent(internalChild);
            }
            this.internalChildren.Clear();
        }

        /// <summary>
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        /// </summary>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <returns>
        /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        public bool Contains(TChild item)
        {
            return this.internalChildren.Contains(item);
        }

        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// 	<paramref name="array"/> is null.
        /// </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="arrayIndex"/> is less than 0.
        /// </exception>
        /// <exception cref="T:System.ArgumentException">
        /// 	<paramref name="array"/> is multidimensional.
        /// -or-
        /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.
        /// -or-
        /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.
        /// -or-
        /// Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
        /// </exception>
        public void CopyTo(TChild[] array, int arrayIndex)
        {
            this.internalChildren.CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </summary>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        /// <returns>
        /// The index of <paramref name="item"/> if found in the list; otherwise, -1.
        /// </returns>
        public int IndexOf(TChild item)
        {
            return this.internalChildren.IndexOf(item);
        }

        /// <summary>
        /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
        /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </exception>
        public void Insert(int index, TChild item)
        {
            this.CheckSetParent(item);
            this.internalChildren.Insert(index, item);
            this.SetParent(item);
        }

        /// <summary>
        /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <returns>
        /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        public bool Remove(TChild item)
        {
            bool remove = this.internalChildren.Remove(item);
            if (remove)
            {
                this.RemoveParent(item);
            }
            return remove;
        }

        /// <summary>
        /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
        /// </exception>
        public void RemoveAt(int index)
        {
            this.RemoveParent(this.internalChildren[index]);
            this.internalChildren.RemoveAt(index);
        }

        /// <summary>
        /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <value></value>
        /// <returns>
        /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        public int Count
        {
            get
            {
                return this.internalChildren.Count;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
        /// </returns>
        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="TChild"/> at the specified index.
        /// </summary>
        /// <value>A Child node.</value>
        public TChild this[int index]
        {
            get
            {
                return this.internalChildren[index];
            }
            set
            {
                this.RemoveParent(this.internalChildren[index]);
                this.SetParent(value);
                this.internalChildren[index] = value;
            }
        }

        #endregion

        private void RemoveParent(TChild oldChild)
        {
            this.CheckRemoveParent(oldChild);
            oldChild.Parent = null;
        }

        private void CheckRemoveParent(TChild oldChild)
        {
            if (oldChild.Parent == null)
            {
                throw new InvalidOperationException("Cant remove parent because the child dont has a parent.");
            }
        }

        private void CheckSetParent(TChild newChild)
        {
            if (newChild.Parent != null)
            {
                throw new InvalidOperationException("Cant set parent because the child already has a parent.");
            }
        }

        private void SetParent(TChild newChild)
        {
            this.CheckSetParent(newChild);
            newChild.Parent = this.listOwner;
        }
    }
}